<?php

namespace App\Console\Commands\Init;

use App\Common\Libs\Json;
use App\Console\BaseCommand;
use App\Models\SysIndustry;
use App\Models\User;
use Illuminate\Support\Facades\Log;

/**
 * 【V2.0.5】行业迁移脚本
 * Class ArticleCounterCommand
 * @package App\Console\Scripts\Counter
 */
class IndustryInitCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @example php artisan init:industry all
     * [!] all 代表执行所有公开方法，相当于合并执行以下两条命令
     *  - php artisan init:industry transfer
     *  - php artisan init:industry static
     * @var string
     */
    protected $signature = 'init:industry {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'init industry';

    /**
     * 转换
     * @return int
     */
    public function transfer()
    {
        $arr = [
            1 => ['1', ' 7'],
            21 => ['11', ' 12'],
            35 => ['37', ' 38'],
            48 => ['44', ' 45'],
            66 => ['51', ' 56'],
            79 => ['31', '35'],
            95 => ['16', '19'],
            140 => ['16', '25'],
            149 => ['1', '5'],
            158 => ['16', '17'],
            165 => ['27', '28'],
            175 => ['44', '49'],
            201 => ['57', '58'],
            213 => ['67', '70'],
            225 => ['67', '68'],
        ];
        $users = User::getInstance()->whereIn('industry_id', array_keys($arr))->get();
        foreach ($users as $user) {
            $user->update([
                'industry_id' => $arr[$user->industry_id][1],
                'industry_parent_id' => $arr[$user->industry_id][0]
            ]);
        }

        // 执行成功返回 1
        return 1;
    }

    /**
     * 静态化
     * @return int
     */
    public function static()
    {
        $firstIndustries = SysIndustry::getInstance()->where('parent_id', 0)->get();
        $data = [];
        foreach ($firstIndustries as $firstIndustry) {
            $firstData = [
                'id' => $firstIndustry->id,
                'parent_id' => $firstIndustry->parent_id,
                'name' => $firstIndustry->name,
                'level' => $firstIndustry->level,
            ];

            $secondIndustries = SysIndustry::getInstance()->where('parent_id', $firstIndustry->id)->get();
            foreach ($secondIndustries as $secondIndustry) {
                $secondIndustry->level = 2;
                $secondIndustry->save();
                $secondIndustryArr = [
                    'id' => $secondIndustry->id,
                    'parent_id' => $secondIndustry->parent_id,
                    'name' => $secondIndustry->name,
                    'level' => $secondIndustry->level,
                ];
                $firstData['child'][] = $secondIndustryArr;
            }
            $data[] = $firstData;
        }

        Log::channel('command')->info(Json::encode($data));

        // 执行成功返回 1
        return 1;
    }

}
